<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click="$emit('changePageNo', pageNo - 1)">
      上一页
    </button>
    <button v-show="startEnd.start > 1" @click="$emit('changePageNo', 1)">
      1
    </button>
    <span v-show="startEnd.start > 2">···</span>

    <button
      :class="{ active: pageNo === index + startEnd.start }"
      v-for="(page, index) in startEnd.end - startEnd.start + 1"
      :key="index"
      @click="$emit('changePageNo', index + startEnd.start)"
    >
      {{ index + startEnd.start }}
    </button>

    <span v-show="startEnd.end < totalPage - 1">···</span>
    <button
      v-show="startEnd.end < totalPage"
      @click="$emit('changePageNo', totalPage)"
    >
      {{ totalPage }}
    </button>
    <button
      :disabled="pageNo === totalPage"
      @click="$emit('changePageNo', pageNo + 1)"
    >
      下一页
    </button>

    <span>共 {{ total }} 条</span>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo", "pageSize", "continues", "total"],
  computed: {
    startEnd() {
      const val = (this.continues - 1) / 2;
      let start, end;
      if (this.totalPage < this.continues) {
        start = 1;
        end = this.totalPage;
      } else {
        start = this.pageNo - val;
        end = this.pageNo + val;
        if (start < 1) {
          start = 1;
          end = this.continues;
        }
        if (end > this.totalPage) {
          start = this.totalPage - this.continues + 1;
          end = this.totalPage;
        }
      }
      return {
        start,
        end,
      };
    },
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
  },
  methods: {},
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: gray;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }

  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>
